package com.course.chapter5;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 自定义锁
 *
 * @version V1.0
 * @ClassName: com.course.chapter5.MyLock.java
 * @author: songxulin
 * @date :  2020-07-02 19:54
 */
public class MyLock implements Lock {

    private Helper helper = new Helper();

    private class Helper extends AbstractQueuedSynchronizer {

        /**
         * 获取锁
         */
        @Override
        protected boolean tryAcquire(int arg) {
            int state = getState();
            if (state == 0) {
                //利用CAS修改state
                if (compareAndSetState(state, arg)) {
                    //设置当前线程占有线程
                    setExclusiveOwnerThread(Thread.currentThread());
                    return true;
                }
            }
            else if(getExclusiveOwnerThread() == Thread.currentThread()){
                //可重入
                setState(getState()+1);
            }
            return false;
        }

        /**
         * 释放锁
         *
         * @param arg
         * @return
         */
        @Override
        protected boolean tryRelease(int arg) {
            int state = getState() - arg;
            //判断释放后是否为0
            if (state <= 0) {
                setExclusiveOwnerThread(null);
                //存在线程安全吗， 没有 (因为只有一个线程能修改)
                setState(state);
                return true;
            }
            //存在线程安全吗， 没有 (因为只有一个线程能修改)
            setState(state);
            return false;
        }

        public Condition newConditionObject(){
            return new ConditionObject();
        }
    }

    @Override
    public void lock() {
        helper.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        helper.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return helper.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, @NotNull TimeUnit unit) throws InterruptedException {
        return helper.tryAcquireNanos(1,unit.toNanos(time));
    }

    @Override
    public void unlock() {
            helper.release(1);
    }

    @NotNull
    @Override
    public Condition newCondition() {
        return helper.newConditionObject();
    }
}
